package com.heaven1949.tmall.order.service.impl;

import cn.hutool.core.convert.Convert;
import com.baomidou.mybatisplus.core.metadata.IPage;
import com.baomidou.mybatisplus.core.toolkit.StringUtils;
import com.baomidou.mybatisplus.core.toolkit.Wrappers;
import com.baomidou.mybatisplus.extension.service.impl.ServiceImpl;
import com.heaven1949.tmall.common.core.dto.ApiResult;
import com.heaven1949.tmall.common.datasource.entity.BaseEntity;
import com.heaven1949.tmall.common.web.exception.ApiAssert;
import com.heaven1949.tmall.order.dto.OrderDTO;
import com.heaven1949.tmall.order.dto.OrderPageQueryDTO;
import com.heaven1949.tmall.order.entity.OrderEntity;
import com.heaven1949.tmall.order.feign.ProductFeignClient;
import com.heaven1949.tmall.order.feign.dto.ProductDTO;
import com.heaven1949.tmall.order.mapper.OrderMapper;
import com.heaven1949.tmall.order.service.IOrderService;
import lombok.RequiredArgsConstructor;
import lombok.extern.slf4j.Slf4j;
import org.springframework.beans.BeanUtils;
import org.springframework.stereotype.Service;

import java.util.Objects;

/**
 * 订单信息service接口实现类
 *
 * @author zhangjian
 * @date 2023-03-08 16:28:52
 */
@Slf4j
@Service
@RequiredArgsConstructor
public class OrderServiceImpl extends ServiceImpl<OrderMapper, OrderEntity> implements IOrderService {

    private final ProductFeignClient productFeignClient;

    @Override
    public IPage<OrderEntity> pageQuery(IPage page, OrderPageQueryDTO dto) {
        log.info("订单信息-分页查询，req：[{}]", dto);
        return page(page, Wrappers.<OrderEntity>lambdaQuery()
                .like(StringUtils.isNotBlank(dto.getUserId()), OrderEntity::getUserId, dto.getUserId())
                .ge(Objects.nonNull(dto.getBeginTime()), BaseEntity::getCreateTime, dto.getBeginTime())
                .le(Objects.nonNull(dto.getEndTime()), BaseEntity::getCreateTime, dto.getEndTime())
                .orderByDesc(OrderEntity::getCreateTime));
    }

    @Override
    public OrderDTO detail(Long id) {
        log.info("订单信息-明细查询，id：[{}]", id);
        OrderEntity entity = getById(id);
        ApiAssert.notNullOrEmpty("订单信息不存在", entity);
        ApiResult<ProductDTO> productResult = productFeignClient.detail(Convert.toLong(entity.getProductId()));
        OrderDTO orderDTO = new OrderDTO();
        BeanUtils.copyProperties(entity, orderDTO);
        orderDTO.setProductDTO(Objects.nonNull(productResult) ? productResult.getData() : null);
        return orderDTO;
    }

}